package com.svo.weitu.activity.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.svo.platform.utils.HttpUtil;
import com.svo.platform.utils.PicUtil;
import com.svo.platform.utils.SvoToast;
import com.svo.platform.utils.TimeConvert;
import com.svo.platform.widget.PushRefreshListView.OnRefreshListener;
import com.svo.weitu.R;
import com.svo.weitu.activity.MainActivity;
import com.svo.weitu.activity.SearchActivity;
import com.svo.weitu.model.db.ListData;
import com.svo.weitu.model.entity.ListEntity;
import com.svo.weitu.util.Cons;
import com.svo.weitu.util.MyUtil;

import java.util.ArrayList;
import java.util.List;

public class TuoFragment extends Fragment implements OnClickListener, SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnItemClickListener {
	private static final int NUM = 10;
	private View root;
	private ArrayList<ListEntity> infos = new ArrayList<>();
	protected MyAdapter adapter;
	private TextView titleTv;
	
	private int id;//分类ID
	private String title;//分类标题

	private int page = 1;
	protected SwipeRefreshLayout swipeRefreshLayout;
	private RecyclerView listView;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		root = inflater.inflate(R.layout.tuo_list, null);
		titleTv = (TextView) root.findViewById(R.id.title);
		root.findViewById(R.id.menu).setOnClickListener(this);
		root.findViewById(R.id.searchIv).setOnClickListener(this);
		root.findViewById(R.id.order).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				((MainActivity)getActivity()).showSecondaryMenu();
			}
		});
		swipeRefreshLayout = (SwipeRefreshLayout) root.findViewById(R.id.swipeRefreshLayout);
		swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_red_light, android.R.color.holo_orange_light,android.R.color.holo_green_light);
		swipeRefreshLayout.setOnRefreshListener(this);
		listView = (RecyclerView) root.findViewById(R.id.listView);
		LinearLayoutManager manager = new LinearLayoutManager(getActivity());
		manager.setOrientation(LinearLayoutManager.VERTICAL);
//		listView.addItemDecoration(new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL));
		listView.setLayoutManager(manager);

		adapter = new MyAdapter(infos);
		adapter.setEnableLoadMore(false);
		adapter.setOnLoadMoreListener(this,listView);
		listView.setAdapter(adapter);
		adapter.setOnItemClickListener(this);
		return root;
	}

	private void refresh() {
		infos.addAll(new ListData(getActivity()).queryAll(id));
		adapter.notifyDataSetChanged();
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Bundle args = getArguments();
		if (args != null) {
			title = args.getString("title");
			id = args.getInt("id", 1);
			titleTv.setText(title);
			refresh();
			if (infos == null || infos.size() == 0) {
				netReq();
			}
		}
	}
	@Override
	public void onResume() {
		super.onResume();
	}
	
	OnRefreshListener refreshListener = new OnRefreshListener() {
		
		@Override
		public void onRefresh() {
			if (infos != null) {
				infos.clear();
			}
			netReq();
		}
	};
	/**
	 * 
	 */
	private void netReq() {
		HttpUtil.get(Cons.gen+"list/get?resId="+id, null, new AsyncHttpResponseHandler(){
			@Override
			public void onFinish() {
				super.onFinish();
				swipeRefreshLayout.setRefreshing(false);
			}
			@Override
			public void onStart() {
				super.onStart();
				swipeRefreshLayout.setRefreshing(true);
			}
			@Override
			public void onSuccess(String arg0) {
				super.onSuccess(arg0);
				List<ListEntity> tmp = new Gson().fromJson(arg0, new TypeToken<List<ListEntity>>(){}.getType());
				if (tmp != null) {
					infos.addAll(tmp);
					adapter.notifyDataSetChanged();
				}
				new Thread(){
					public void run() {
						new ListData(getActivity()).insert(infos,"tuo");
					};
				}.start();
			}
		});
		
	}
	protected void reqOld() {
		page++;
		if (MyUtil.isNetworkAvailable(getActivity())) {
			if (infos != null && infos.size() > 0) {
				HttpUtil.get(Cons.gen+"list/get?resId="+id+"&page="+page+"&num="+NUM, null, new AsyncHttpResponseHandler(){

					@Override
					public void onSuccess(String arg0) {
						super.onSuccess(arg0);
						List<ListEntity> tmpInfos = new Gson().fromJson(arg0, new TypeToken<List<ListEntity>>(){}.getType());
						if (tmpInfos != null && tmpInfos.size() > 0) {
							infos.addAll(tmpInfos);
							adapter.notifyDataSetChanged();
							adapter.loadMoreComplete();
						}else {
							adapter.loadMoreEnd();
						}
					}
					@Override
					public void onFailure(Throwable arg0, String arg1) {
						super.onFailure(arg0, arg1);
						adapter.loadMoreComplete();
					}
				});
			}
		}else {
			SvoToast.showHint(getActivity(), "网络不可用", Toast.LENGTH_SHORT);
		}
	}
	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.searchIv) {
			startActivity(new Intent(getActivity(), SearchActivity.class));
		}else {
			MainActivity mainActivity = (MainActivity) getActivity();
			mainActivity.showMenu();
		}
	}

	/**
	 * @param entity
	 * @param pics
	 * @param infos2 
	 */
	private void openPicBrowser(final ListEntity entity, ArrayList<String> pics, List<ListEntity> infos2) {
		new MyUtil().handlePics(entity, pics,getActivity(),infos);
		getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}
	
	public static int height = (int) (193*1.5);
	public static int width = 480;

	@Override
	public void onRefresh() {
		netReq();
	}

	@Override
	public void onLoadMoreRequested() {
		reqOld();
	}

	@Override
	public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
		final ListEntity entity = infos.get(position);
		String urls = entity.getUrls();
		String[] arrs = urls.split(";");
		ArrayList<String> pics =  MyUtil.arrToList(arrs);
		openPicBrowser(entity, pics,infos);
	}

	private class MyAdapter extends BaseQuickAdapter<ListEntity,BaseViewHolder> {
		List<ListEntity> data;
		public MyAdapter(List<ListEntity> data) {
			super(R.layout.reader_list_item,data);
			this.data = data;
			DisplayMetrics metrics = getResources().getDisplayMetrics();
			height = (int) (metrics.density * 193);
			width = metrics.widthPixels;
		}

		@Override
		protected void convert(BaseViewHolder helper, ListEntity entity) {
			helper.setText(R.id.display_time, TimeConvert.formatDate(entity.getTime()))
					.setText(R.id.title, entity.getTitle())
					.setText(R.id.item_num_likes, entity.getLoves()+"");
			ImageView imageView = helper.getView(R.id.content_thumbnail);
			String thumbnail = entity.getThumbnail();
			if (TextUtils.isEmpty(thumbnail)) {
				String[] urls = entity.getUrls().split(";");
				PicUtil.displayImage(getActivity(), urls[0], imageView);
			}else {
				PicUtil.displayImage(getActivity(), thumbnail, imageView);
			}
		}

	}

}
